
<script setup>
import { ref, reactive } from 'vue'
import { baseURL } from '@/api/request'
import { formatDate } from '@/utils/format'
import { getVideoList, getVideoDetail, editVideo, delVideo, addVideo, updatePlaybackCount } from '@/api/video'
import { ElMessageBox, ElMessage, ElDialog, ElImage, ElForm, ElFormItem, ElInput, ElButton, ElInputNumber, ElDatePicker, ElSelect, ElOption } from 'element-plus'

const videos = ref([])
const queryParams = ref({
  pageNo: 1,
  size: 5,
  search: ''
})
const total = ref(0)

const fetchVideos = async () => {
  const { data } = await getVideoList(queryParams.value)
  console.log(data); // 打印数据以调试
  videos.value = data.records.map(video => ({
    ...video,
    vImgUrl: `http://localhost:9999/r/video/musicMV/${video.v_img}`
  }))
  total.value = data.total
}
fetchVideos()

// 分页
const change = (pageNo) => {
  queryParams.value.pageNo = pageNo
  fetchVideos()
}

// 搜索
const submitForm = () => {
  fetchVideos()
}

// 区域映射表 {id: name}
const regionsMap = ref({
  1: '区域A',
  2: '区域B'
})

// 当前选中的视频详情
const currentVideo = ref(null)
const dialogVisible = ref(false)

let lastClickTime = null;

const playingVideo = async row => {
  const currentTime = Date.now();
  if (lastClickTime && (currentTime - lastClickTime < 3000)) {
    ElMessage.warning('点击视频过快');
    return;
  }
  lastClickTime = currentTime;

  const { data } = await getVideoDetail(row.id)
  console.log('Fetching video details for ID:', row.id);
  console.log('Video fetched successfully:', data);

  // 确保 vUrl 和 vImg 存在且不为空
  if (!data.v_url || !data.v_img) {
    ElMessage.error('视频或图片地址无效');
    return;
  }

  // 使用后端地址拼接路径
  data.vUrl = `http://localhost:9999/r${data.v_url}`;
  data.vImg = `http://localhost:9999/r/video/musicMV/${data.v_img}`;

  currentVideo.value = data;
  dialogVisible.value = true;

  // 更新播放量    这是一个注释
  try {
    console.log(`Updating playback count for video ID: ${row.id}`);
    await updatePlaybackCount(row.id);
    ElMessage.success('播放量已更新');
    // 刷新视频列表
    fetchVideos();
  } catch (error) {
    console.error('更新播放量失败:', error);
    console.error('Failed URL:', `${baseURL}/video/update-Playback`);
    ElMessage.error('更新播放量失败');
  }
}

// 编辑相关状态
const editDialogVisible = ref(false)
const editingVideo = ref({})

const openEditDialog = (row) => {
  editingVideo.value = { ...row }
  editDialogVisible.value = true
}

const saveEditedVideo = async () => {
  try {
    await editVideo(editingVideo.value)
    ElMessage.success('编辑成功')
    fetchVideos()
    editDialogVisible.value = false
  } catch (error) {
    console.error('编辑视频失败:', error)
    ElMessage.error('编辑失败')
  }
}

// 删除
const deleteVideoRow = async row => {
  ElMessageBox.confirm('确定要删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await delVideo(row.id)
      ElMessage.success('删除成功')
      fetchVideos()
    } catch (error) {
      console.error('删除视频失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 添加新视频相关状态
const addDialogVisible = ref(false)
const newVideo = reactive({
  v_name: '',
  v_author: '',
  v_playback: 0,
  v_createtime: '',
  regionid: 1,
  versionid: 1,
  v_url: '',
  v_img: ''
})

const openAddDialog = () => {
  newVideo.v_name = ''
  newVideo.v_author = ''
  newVideo.v_playback = 0
  newVideo.v_createtime = ''
  newVideo.regionid = 1
  newVideo.versionid = 1
  newVideo.v_url = ''
  newVideo.v_img = ''
  addDialogVisible.value = true
}

const rules = ref({
  v_name: [{ required: true, message: '请输入视频名称', trigger: 'blur' }],
  v_author: [{ required: true, message: '请输入作者', trigger: 'blur' }],
  v_playback: [{ required: true, message: '请输入播放量', trigger: 'blur' }],
  v_createtime: [{ required: true, message: '请选择创建日期', trigger: 'change' }],
  v_url: [{ required: true, message: '请输入视频URL', trigger: 'blur' }],
  v_img: [{ required: true, message: '请输入图片URL', trigger: 'blur' }],
  regionid: [{ required: true, message: '请选择区域ID', trigger: 'blur' }],
  versionid: [{ required: true, message: '请输入版本ID', trigger: 'blur' }]
})

const formRef = ref(null)

const saveNewVideo = async () => {
  formRef.value.validate((valid) => {
    if (valid) {
      addVideo(newVideo)
        .then(() => {
          ElMessage.success('添加成功')
          fetchVideos()
          addDialogVisible.value = false
        })
        .catch(error => {
          console.error('添加视频失败:', error)
          ElMessage.error('添加失败')
        })
    } else {
      console.error('表单验证失败')
      return false
    }
  })
}
</script>

<template>
  <el-card style="max-width: 100%">
    <template #header>
      <div class="card-header">
        <el-form :inline="true" :model="queryParams" label-width="auto" class="demo-form-inline">
          <el-form-item label="视频名称">
            <el-input placeholder="请输入视频信息" clearable v-model="queryParams.search" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm">搜</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="success" @click="openAddDialog">添加视频</el-button>
          </el-form-item>
        </el-form>
      </div>
    </template>
    <el-table :data="videos" style="width: 100%">
      <el-table-column prop="id" label="编号" width="80" />
      <el-table-column prop="v_name" label="视频名称" min-width="140">
        <template #default="{ row }">
          <div style="display: flex; align-items: center;">
            <el-image
              style="margin-left: 10px; cursor: pointer; width: 100px; height: 80px;"
              :src="row.vImgUrl"
              fit="cover"
              preview-src-list="[row.vImgUrl]"
              :preview-teleported="true"
            ></el-image>
           <a href="#" @click.prevent="playingVideo(row)" class="video-name" style="margin-left: 20px;">{{ row.v_name }}</a>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="v_author" label="作者" width="150" />
      <el-table-column prop="v_playback" label="播放量" width="120" />
      <el-table-column prop="v_createtime" label="日期" :formatter="formatDate" width="150" />
      <el-table-column label="操作" width="150">
        <template #default="{ row }">
          <div style="display: flex; justify-content: space-between;">
            <el-button type="primary" @click="openEditDialog(row)">编辑</el-button>
            <el-button type="danger" @click="deleteVideoRow(row)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="example-pagination-block">
      <el-pagination background layout="prev, pager, next" @current-change="change" :total="total"
        :page-size="queryParams.size" />
    </div>
  </el-card>
  
  <!-- 视频播放器组件 -->
  <VideoPlayer :videos="videos" :regions="regionsMap" :autoPlay="true" />

  <!-- 模态框 -->
  <el-dialog title="视频详情" v-model="dialogVisible" width="60%" center>
    <div v-if="currentVideo">
      <el-image :src="currentVideo.vImg" style="width: 100%; height: auto;"></el-image>
      <div style="margin-top: 20px;">
        <h3>视频地址:</h3>
        <p>{{ currentVideo.vUrl }}</p>
        <video controls style="width: 100%;">
          <source :src="currentVideo.vUrl" type="video/mp4">
          您的浏览器不支持 video 标签。
        </video>
      </div>
    </div>
  </el-dialog>

  <!-- 编辑视频对话框 -->
  <el-dialog title="编辑视频" v-model="editDialogVisible" width="40%" center>
    <el-form :model="editingVideo" label-width="auto">
      <el-form-item label="视频名称" prop="v_name" :rules="rules.v_name">
        <el-input v-model="editingVideo.v_name"></el-input>
      </el-form-item>
      <el-form-item label="作者" prop="v_author" :rules="rules.v_author">
        <el-input v-model="editingVideo.v_author"></el-input>
      </el-form-item>
      <el-form-item label="播放量" prop="v_playback" :rules="rules.v_playback">
        <el-input-number v-model="editingVideo.v_playback" :min="0"></el-input-number>
      </el-form-item>
      <el-form-item label="创建日期" prop="v_createtime" :rules="rules.v_createtime">
        <el-date-picker v-model="editingVideo.v_createtime" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="区域ID" prop="regionid" :rules="rules.regionid">
        <el-select v-model="editingVideo.regionid">
          <el-option v-for="(name, id) in regionsMap" :key="id" :label="name" :value="parseInt(id)"></el-option>
        </el-select>
      </el-form-item> -->
       <el-form-item label="区域ID" prop="regionid" :rules="rules.regionid">
        <el-input-number v-model="editingVideo.regionid" :min="1"></el-input-number>
      </el-form-item>
      <el-form-item label="版本ID" prop="versionid" :rules="rules.versionid">
        <el-input-number v-model="editingVideo.versionid" :min="1"></el-input-number>
      </el-form-item>
      <el-form-item label="视频URL" prop="v_url" :rules="rules.v_url">
        <el-input v-model="editingVideo.v_url"></el-input>
      </el-form-item>
      <el-form-item label="图片URL" prop="v_img" :rules="rules.v_img">
        <el-input v-model="editingVideo.v_img"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEditedVideo">确 定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 添加视频对话框 -->
  <el-dialog title="添加视频" v-model="addDialogVisible" width="40%" center>
    <el-form :model="newVideo" label-width="auto" :rules="rules" ref="formRef">
      <el-form-item label="视频名称" prop="v_name">
        <el-input v-model="newVideo.v_name"></el-input>
      </el-form-item>
      <el-form-item label="作者" prop="v_author">
        <el-input v-model="newVideo.v_author"></el-input>
      </el-form-item>
      <el-form-item label="播放量" prop="v_playback">
        <el-input-number v-model="newVideo.v_playback" :min="0"></el-input-number>
      </el-form-item>
      <el-form-item label="创建日期" prop="v_createtime">
        <el-date-picker v-model="newVideo.v_createtime" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
      </el-form-item>
      <el-form-item label="图片URL" prop="v_img">
        <el-input v-model="newVideo.v_img"></el-input>
      </el-form-item>
      <el-form-item label="视频URL" prop="v_url">
        <el-input v-model="newVideo.v_url"></el-input>
      </el-form-item>
      <!-- <el-form-item label="区域ID" prop="regionid">
        <el-select v-model="newVideo.regionid">
          <el-option v-for="(name, id) in regionsMap" :key="id" :label="name" :value="parseInt(id)"></el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="区域ID" prop="regionid">
        <el-input-number v-model="newVideo.regionid" :min="1"></el-input-number>
      </el-form-item>
      <el-form-item label="版本ID" prop="versionid">
        <el-input-number v-model="newVideo.versionid" :min="1"></el-input-number>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveNewVideo">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.el-card {
  min-height: 100%;
  width: 100vw;
}
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.demo-form-inline .el-form-item {
  margin-bottom: 0;
}
.video-name {
  text-decoration: none; /* 移除下划线 */
  color: #007bff; /* 设置字体颜色 */
  margin-right: 10px; /* 增加一些间距 */
}
</style>